package com.customization.commons;


import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.*;
import weaver.workflow.request.RequestManager;
import weaver.workflow.workflow.WorkflowRequestComInfo;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



/**
 * Created by liutaihong on 16-06-17.
 * 描述：日志及取值工具类
 */
public class CustomAction extends BaseBean {


    protected HashMap<String, String> mainMap;//主字段的值
    protected HashMap<String, HashMap<String, HashMap<String, String>>> detailMap;//所有明细表的值

    protected WSBaseInfo wsBaseInfo;
    protected static int wf_creater;
    protected static int wf_formid;
    protected static int wf_isbill;
    protected static String formtablename;
    protected int wf_user;

    //增加一个内部锁
    protected Object lock = new Object();


    public CustomAction() {


        if (mainMap == null && detailMap == null && wsBaseInfo == null) {//判断对象是否为空
            synchronized (lock) {
                Console.log("CustomAction 被实例化");
                mainMap = new HashMap<String, String>();//主字段的值
                detailMap = new HashMap<String, HashMap<String, HashMap<String, String>>>();//所有明细表的值
                wsBaseInfo = new WSBaseInfo();
                wf_creater = 0;
                wf_formid = 0;
                wf_isbill = 0;
                formtablename = "";
                wf_user = 0;
            }
        }

    }

    /**
     * 检查上线之后发起的流程
     *
     * @param requestInfo
     * @return
     */
    public boolean checkNewRequest(RequestInfo requestInfo) {


        String oaUptime = Util.null2String(new BaseBean().getPropValue("angel_fna", "oaUptime"));
        String createDatetime = requestInfo.getRequestManager().getCreatedate() + " " + requestInfo.getRequestManager().getCreatetime();
        if (oaUptime.equals("")) {
            return false;
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date oaUptime_Date = sdf.parse(oaUptime);
            Date createtime_Date = sdf.parse(createDatetime);

            boolean flag = oaUptime_Date.getTime() >= createtime_Date.getTime();
            Console.log("上线时间:" + oaUptime_Date + ";流程" + requestInfo.getRequestid() + "发起时间:" + createtime_Date + ";上线之前发起流程:" + flag);
            return flag;
        } catch (ParseException e) {
            e.printStackTrace();
            return true;
        }

    }

    public boolean checkNewRequest() {


        String oaUptime = "2021-01-01 01:04:00";
        String createDatetime = "2021-01-01 01:02:00";
        if (oaUptime.equals("")) {
            return true;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date oaUptime_Date = sdf.parse(oaUptime);
            Date createtime_Date = sdf.parse(createDatetime);

            boolean flag = oaUptime_Date.getTime() <= createtime_Date.getTime();
            return flag;

        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }


    }

    public synchronized Map<String, Object> initRequestData(RequestInfo requestInfo) {
        Map<String, Object> hashMap = new HashMap();

        RequestManager rm = requestInfo.getRequestManager();

        //System.out.println("select * from formtable_main_"+Math.abs(rm.getFormid())+" where requestid='"+rm.getRequestid()+"'");
        RequestManager RequestManager = requestInfo.getRequestManager();
        wf_formid = RequestManager.getFormid();//流程表单id
        wf_creater = RequestManager.getCreater();//流程创建人
        wf_isbill = RequestManager.getIsbill();//是否为单据

        wf_user = RequestManager.getUser().getUID();//当前操作者


        mainMap.put("requestname", requestInfo.getDescription());//流程标题
        mainMap.put("requestid", requestInfo.getRequestid());//流程id
        mainMap.put("creatorid", requestInfo.getCreatorid());//流程创建人ID
        mainMap.put("workflowid", requestInfo.getWorkflowid());


        try {
            ResourceComInfo rci = new ResourceComInfo();
            DepartmentComInfo dci = new DepartmentComInfo();

            wsBaseInfo.setFormTablename(rm.getBillTableName());


            wsBaseInfo.setCreater_departmentcode(dci.getDepartmentCode(rci.getDepartmentID("" + wf_creater)));
            wsBaseInfo.setCreater_departmentid(rci.getDepartmentID("" + wf_creater));
            wsBaseInfo.setCreater_departmentname(dci.getDepartmentname(rci.getDepartmentID("" + wf_creater)));
            wsBaseInfo.setCreater_department_codeAndName(dci.getDepartmentCode(rci.getDepartmentID("" + wf_creater)) + "|" + dci.getDepartmentname(rci.getDepartmentID("" + wf_creater)));


            wsBaseInfo.setCreater_lastname(rci.getLastname("" + wf_creater));
            //wsBaseInfo.setCreater_workcode(rci.getWorkcode("" + wf_creater));
            //wsBaseInfo.setCreater_workcodeAndName(rci.getWorkcode("" + wf_creater) + "|" + rci.getLastname("" + wf_creater));


            wsBaseInfo.setCurrent_departmentcode(dci.getDepartmentname(rci.getDepartmentID("" + wf_user)));
            wsBaseInfo.setCurrent_departmentid(rci.getDepartmentID("" + wf_user));
            wsBaseInfo.setCurrent_departmentname(dci.getDepartmentCode(rci.getDepartmentID("" + wf_user)));
            wsBaseInfo.setCurrent_department_codeAndName(dci.getDepartmentname(rci.getDepartmentID("" + wf_user)) + "|" + dci.getDepartmentCode(rci.getDepartmentID("" + wf_user)));

            wsBaseInfo.setCurrent_lastname(rci.getLastname("" + wf_user));
            wsBaseInfo.setCurrent_workcode(rci.getWorkcode("" + wf_user));
            wsBaseInfo.setCurrent_workcodeAndName(rci.getWorkcode("" + wf_user) + "|" + rci.getLastname("" + wf_user));
          /*
            RecordSet recordSet = new RecordSet();
            recordSet.execute("select  TEXTFIELD2  from  HRMRESOURCE where id='" + wf_user + "'");
            if (recordSet.first()) {
                wsBaseInfo.setCurrent_sap_username(recordSet.getString("TEXTFIELD2"));
            }
            */

            RecordSet recordSet = new RecordSet();
            String accounttype="";
            String BELONGTO="";
            recordSet.execute("select  TEXTFIELD2,ACCOUNTTYPE,BELONGTO  from  HRMRESOURCE where id='" + wf_user + "'");
            if (recordSet.first()) {
                wsBaseInfo.setCurrent_sap_username(recordSet.getString("TEXTFIELD2"));
                accounttype=recordSet.getString("ACCOUNTTYPE");
                BELONGTO=recordSet.getString("BELONGTO");
            }
            if(accounttype.equals("1")){
                wsBaseInfo.setCreater_workcode(rci.getWorkcode(BELONGTO));
                wsBaseInfo.setCreater_workcodeAndName(rci.getWorkcode("" + BELONGTO) + "|" + rci.getLastname("" + wf_creater));
            }else{
                wsBaseInfo.setCreater_workcode(rci.getWorkcode(""+wf_creater));
                wsBaseInfo.setCreater_workcodeAndName(rci.getWorkcode("" + wf_creater) + "|" + rci.getLastname("" + wf_creater));
            }

            recordSet.execute(" select APPROVER_WORKCODE from UF_DISPATCHSSF WHERE   request_id='" + requestInfo.getRequestid() + "'");
            if (recordSet.first()) {
                mainMap.put("sap_sname", recordSet.getString("APPROVER_WORKCODE"));
            } else {
                mainMap.put("sap_sname", "");
            }

            wsBaseInfo.setFormid(Math.abs(rm.getFormid()));
            recordSet.execute("select  REQUESTMARK  from  WORKFLOW_REQUESTBASE  where requestid='" + requestInfo.getRequestid() + "'");
            if (recordSet.first()) {
                mainMap.put("requestmark", recordSet.getString("REQUESTMARK"));//流程id
            }


            mainMap.put("createrworkcode", rci.getWorkcode("" + wf_creater));//流程创建人工号
            mainMap.put("createrlastname", rci.getLastname("" + wf_creater));//流程创建人姓名
            mainMap.put("createrdepartmentid", rci.getDepartmentID("" + wf_creater));//流程创建人部门ID
            mainMap.put("createrdepartmentname", dci.getDepartmentname(rci.getDepartmentID("" + wf_creater)));//流程创建人部门名称
            mainMap.put("createrdepartmentcode", dci.getDepartmentCode(rci.getDepartmentID("" + wf_creater)));//流程创建人部门编号

            mainMap.put("currentworkcode", rci.getWorkcode("" + wf_user));//当前操作人工号
            mainMap.put("currentlastname", rci.getLastname("" + wf_user));//当前操作人姓名
            mainMap.put("currentdepartmentid", rci.getDepartmentID("" + wf_user));//当前操作人部门ID
            mainMap.put("currentdepartmentname", dci.getDepartmentname(rci.getDepartmentID("" + wf_user)));//当前操作人部门名称
            mainMap.put("currentdepartmentcode", dci.getDepartmentCode(rci.getDepartmentID("" + wf_user)));//当前操作人部门编号


        } catch (Exception e) {
            System.out.println("流程基础信息获取:" + e.toString());
        }
        // System.out.println(".......>"+wsBaseInfo.getSys());

        /**/
        System.out.println("requestid:" + requestInfo.getRequestid());
        Property[] properties = requestInfo.getMainTableInfo().getProperty();// 获取表单主字段信息
        for (int i = 0; i < properties.length; i++) {// 主表数据
            String name = properties[i].getName().toLowerCase();
            String value = Util.null2String(properties[i].getValue());
            //System.out.println("formtable_main_"+Math.abs(wf_formid)+"."+name+"："+ Util.null2String(value));
            mainMap.put(name, Util.null2String(value));
            //writeLog(name + ":" + value);
        }

        DetailTable[] detailtable = null;
        try {
            detailtable = requestInfo.getDetailTableInfo().getDetailTable();// 获取明细表
            if (detailtable.length > 0) {

                for (int i = 1; i <= detailtable.length; i++) {//遍历明细表
                    HashMap<String, HashMap<String, String>> rowList = new LinkedHashMap<String, HashMap<String, String>>();
                    DetailTable dt = detailtable[i - 1];
                    Row[] s = dt.getRow();

                    for (int j = 1; j <= s.length; j++) {
                        HashMap<String, String> rowMap = new LinkedHashMap<String, String>();
                        Row r = s[j - 1];

                        Cell[] c = r.getCell();
                        for (int k = 0; k < c.length; k++) {
                            Cell c1 = c[k];
                            String name = c1.getName().toLowerCase();
                            String value = c1.getValue();

                            //System.out.println(i+""+"-"+name+":"+value);
                            rowMap.put(name, Util.null2String(value));
                        }
                        if (rowMap.size() > 0) {
                            rowList.put(r.getId(), rowMap);
                        }

                    }
                    detailMap.put(dt.getTableDBName().substring(dt.getTableDBName().lastIndexOf("_") + 1), rowList);
                }
            }

        } catch (Exception e) {

        }

        RecordSet rst = new RecordSet();


        String requestid = requestInfo.getRequestid();
        String requestname = "";
        String workflowid = "";
        String formid = "";
        String creater = "";
        String createdate = "";
        String createtime = "";

        //获取流程基础信息
        String sqls = " select wr.requestname,wr.workflowid,wb.formid, wr.creater,wr.createdate,wr.createtime from WORKFLOW_REQUESTBASE  wr ,workflow_base wb " +
                " where  requestid='" + requestid + "' and wr.workflowid =wb.id ";
        //  Console.log(sqls);
        rst.execute(sqls);
        if (rst.next()) {
            requestname = rst.getString("requestname");
            workflowid = rst.getString("workflowid");
            formid = rst.getString("formid");
            creater = rst.getString("creater");
            createdate = rst.getString("createdate");
            createtime = rst.getString("createtime");
        }

        //获取流程主表表名
        sqls = "select tablename  from WORKFLOW_BILL where WORKFLOW_BILL.id='" + formid + "'";
        rst.execute(sqls);
        //Console.log(sqls);
        rst.first();
        String tablename = rst.getString("tablename");
        wsBaseInfo.setFormTablename(tablename);

 /*
        //获取流程主表数据
        sqls="select  *  from "+tablename+" where requestid='"+requestid+"'";
        rst.execute(sqls);
        // Console.log(sqls);
        if(rst.next()){
            String cloumn [] =rst.getColumnName();
            for (String c:cloumn) {
                String name = c.toLowerCase();
                String value = Util.null2String(rst.getString(c));
                mainMap.put(name, Util.null2String(value));
            }
        }


        sqls="select detailtable from WORKFLOW_BILLFIELD where billid ='"+formid+"' and (detailtable is not null or detailtable <>''）  group by detailtable order by  detailtable";
        rst.execute(sqls);
        while(rst.next()){
            String  detailtablename= Util.null2String(rst.getString("detailtable"));
            //  Console.log("detailtablename："+detailtablename);
            if(!detailtablename.equals("")){
                HashMap<String, HashMap<String, String>> rowList = new LinkedHashMap<String, HashMap<String, String>>();
                String sql="select  dt.*  from "+detailtablename+" dt,"+tablename+" t  where  t.id=dt.mainid and t.requestid='"+requestid+"'";
                rs.execute(sql);
                //  Console.log(sql);
                while(rs.next()){
                    String cloumnArr [] =rs.getColumnName();
                    HashMap<String, String> rowMap = new LinkedHashMap<String, String>();
                    for (String c:cloumnArr) {
                        String name = c.toLowerCase();
                        String value = Util.null2String(rs.getString(c));
                        rowMap.put(name, Util.null2String(value));
                    }
                    rowList.put(rs.getString("id"),rowMap);
                }
                detailMap.put(detailtablename.substring(detailtablename.lastIndexOf("_")+1), rowList);
            }
        }


        Console.log("jdbc 取值 mainMap:"+mainMap.toString());
        Console.log("jdbc 取值 detailMap:"+detailMap.toString());
*/
        hashMap.put("mainMap", mainMap);
        hashMap.put("detailMap", detailMap);
        hashMap.put("wsBaseInfo", wsBaseInfo);
        hashMap.put("wf_creater", wf_creater);
        hashMap.put("wf_formid", wf_formid);
        hashMap.put("wf_isbill", wf_isbill);
        hashMap.put("formtablename", formtablename);
        hashMap.put("wf_user", wf_user);
        return hashMap;
    }


    /**
     * 获取主表数据
     * 在流程action里面初始化后只需要通过Map就能快速的取到对应的主表的值
     * <p>
     * 适用场景：
     * 1.通过获取表名，然后使用SQL语句查询你要的主表数据(升级之后表名还会出错)。
     * 2.通过遍历requestInfo.getMainTableInfo().getProperty()做判断匹配值。
     * <p>
     * 使用：
     * 获取流程名称：map.get("requestName");
     * 获取流程requestid：map.get("requestId");
     * 获取流程创建人：map.get("creatorId");
     * 获取流程类型id：map.get("workflowId");
     *
     * @param requestInfo 流程对象
     * @return mainMap 主表的列名和值
     */
    public synchronized void getWorkflowDataValue(RequestInfo requestInfo) {
        /*
        Console.log(" 执行：getWorkflowDataValue");
        long waittime=ProcessingUtil.start();
        Console.log(requestInfo.getRequestid()+"等待"+waittime+"ms");
        */

        RequestManager rm = requestInfo.getRequestManager();

        //System.out.println("select * from formtable_main_"+Math.abs(rm.getFormid())+" where requestid='"+rm.getRequestid()+"'");
        RequestManager RequestManager = requestInfo.getRequestManager();
        wf_formid = RequestManager.getFormid();//流程表单id
        wf_creater = RequestManager.getCreater();//流程创建人
        wf_isbill = RequestManager.getIsbill();//是否为单据

        wf_user = RequestManager.getUser().getUID();//当前操作者


        mainMap.put("requestname", requestInfo.getDescription());//流程标题
        mainMap.put("requestid", requestInfo.getRequestid());//流程id
        mainMap.put("creatorid", requestInfo.getCreatorid());//流程创建人ID
        mainMap.put("workflowid", requestInfo.getWorkflowid());


        try {
            ResourceComInfo rci = new ResourceComInfo();
            DepartmentComInfo dci = new DepartmentComInfo();

            wsBaseInfo.setFormTablename(rm.getBillTableName());


            wsBaseInfo.setCreater_departmentcode(dci.getDepartmentCode(rci.getDepartmentID("" + wf_creater)));
            wsBaseInfo.setCreater_departmentid(rci.getDepartmentID("" + wf_creater));
            wsBaseInfo.setCreater_departmentname(dci.getDepartmentname(rci.getDepartmentID("" + wf_creater)));
            wsBaseInfo.setCreater_department_codeAndName(dci.getDepartmentCode(rci.getDepartmentID("" + wf_creater)) + "|" + dci.getDepartmentname(rci.getDepartmentID("" + wf_creater)));


            wsBaseInfo.setCreater_lastname(rci.getLastname("" + wf_creater));
            //wsBaseInfo.setCreater_workcode(rci.getWorkcode("" + wf_creater));
            //wsBaseInfo.setCreater_workcodeAndName(rci.getWorkcode("" + wf_creater) + "|" + rci.getLastname("" + wf_creater));


            wsBaseInfo.setCurrent_departmentcode(dci.getDepartmentname(rci.getDepartmentID("" + wf_user)));
            wsBaseInfo.setCurrent_departmentid(rci.getDepartmentID("" + wf_user));
            wsBaseInfo.setCurrent_departmentname(dci.getDepartmentCode(rci.getDepartmentID("" + wf_user)));
            wsBaseInfo.setCurrent_department_codeAndName(dci.getDepartmentname(rci.getDepartmentID("" + wf_user)) + "|" + dci.getDepartmentCode(rci.getDepartmentID("" + wf_user)));

            wsBaseInfo.setCurrent_lastname(rci.getLastname("" + wf_user));
            wsBaseInfo.setCurrent_workcode(rci.getWorkcode("" + wf_user));
            wsBaseInfo.setCurrent_workcodeAndName(rci.getWorkcode("" + wf_user) + "|" + rci.getLastname("" + wf_user));
            RecordSet recordSet = new RecordSet();
            String accounttype="";
            String BELONGTO="";
            recordSet.execute("select  TEXTFIELD2,ACCOUNTTYPE,BELONGTO  from  HRMRESOURCE where id='" + wf_user + "'");
            if (recordSet.first()) {
                wsBaseInfo.setCurrent_sap_username(recordSet.getString("TEXTFIELD2"));
                accounttype=recordSet.getString("ACCOUNTTYPE");
                BELONGTO=recordSet.getString("BELONGTO");
            }
            if(accounttype.equals("1")){
                wsBaseInfo.setCreater_workcode(rci.getWorkcode(BELONGTO));
                wsBaseInfo.setCreater_workcodeAndName(rci.getWorkcode("" + BELONGTO) + "|" + rci.getLastname("" + wf_creater));

            }else{
                wsBaseInfo.setCreater_workcode(rci.getWorkcode(""+wf_creater));
                wsBaseInfo.setCreater_workcodeAndName(rci.getWorkcode("" + wf_creater) + "|" + rci.getLastname("" + wf_creater));

            }

            //2021/3/3 16:12 lth  END 子账号获取主账号的员工编号
            wsBaseInfo.setFormid(Math.abs(rm.getFormid()));

            recordSet.execute("select  REQUESTMARK  from  WORKFLOW_REQUESTBASE  where requestid='" + requestInfo.getRequestid() + "'");
            if (recordSet.first()) {
                mainMap.put("requestmark", recordSet.getString("REQUESTMARK"));//流程id
            }


            mainMap.put("createrworkcode", rci.getWorkcode("" + wf_creater));//流程创建人工号
            mainMap.put("createrlastname", rci.getLastname("" + wf_creater));//流程创建人姓名
            mainMap.put("createrdepartmentid", rci.getDepartmentID("" + wf_creater));//流程创建人部门ID
            mainMap.put("createrdepartmentname", dci.getDepartmentname(rci.getDepartmentID("" + wf_creater)));//流程创建人部门名称
            mainMap.put("createrdepartmentcode", dci.getDepartmentCode(rci.getDepartmentID("" + wf_creater)));//流程创建人部门编号

            mainMap.put("currentworkcode", rci.getWorkcode("" + wf_user));//当前操作人工号
            mainMap.put("currentlastname", rci.getLastname("" + wf_user));//当前操作人姓名
            mainMap.put("currentdepartmentid", rci.getDepartmentID("" + wf_user));//当前操作人部门ID
            mainMap.put("currentdepartmentname", dci.getDepartmentname(rci.getDepartmentID("" + wf_user)));//当前操作人部门名称
            mainMap.put("currentdepartmentcode", dci.getDepartmentCode(rci.getDepartmentID("" + wf_user)));//当前操作人部门编号


        } catch (Exception e) {
            System.out.println("流程基础信息获取:" + e.toString());
        }
        // System.out.println(".......>"+wsBaseInfo.getSys());

        /*
        System.out.println("requestid:" + requestInfo.getRequestid());
        Property[] properties = requestInfo.getMainTableInfo().getProperty();// 获取表单主字段信息
        for (int i = 0; i < properties.length; i++) {// 主表数据
            String name = properties[i].getName().toLowerCase();
            String value = Util.null2String(properties[i].getValue());
            //System.out.println("formtable_main_"+Math.abs(wf_formid)+"."+name+"："+ Util.null2String(value));
            mainMap.put(name, Util.null2String(value));
            //writeLog(name + ":" + value);
        }

        DetailTable[] detailtable = null;
        try {
            detailtable = requestInfo.getDetailTableInfo().getDetailTable();// 获取明细表
            if (detailtable.length > 0) {

                for (int i = 1; i <= detailtable.length; i++) {//遍历明细表
                    HashMap<String, HashMap<String, String>> rowList = new LinkedHashMap<String, HashMap<String, String>>();
                    DetailTable dt = detailtable[i-1];
                    Row[] s = dt.getRow();

                    for (int j = 1; j <= s.length; j++) {
                        HashMap<String, String> rowMap = new LinkedHashMap<String, String>();
                        Row r = s[j-1];

                        Cell[] c = r.getCell();
                        for (int k = 0; k < c.length; k++) {
                            Cell c1 = c[k];
                            String name = c1.getName().toLowerCase();
                            String value = c1.getValue();

                            //System.out.println(i+""+"-"+name+":"+value);
                            rowMap.put(name, Util.null2String(value));
                        }
                        if (rowMap.size() > 0) {
                            rowList.put(r.getId(), rowMap);
                        }

                    }
                    detailMap.put(dt.getTableDBName().substring(dt.getTableDBName().lastIndexOf("_")+1), rowList);
                }
            }

        } catch (Exception e) {

        }


         */

        //  Console.log("-------------requestid:"+requestInfo.getRequestid()+"--------------");
        // Console.log("Request对象取值 mainMap:"+mainMap.toString());
        // Console.log("Request对象取值 detailMap:"+detailMap.toString());
        //detailMap.clear();
        //mainMap.clear();


        //  Console.log("Request对象取值 初始化后:"+mainMap.toString());
        // Console.log("Request对象取值 初始化后:"+detailMap.toString());


        /* */
        RecordSet rst = new RecordSet();
        RecordSet rs = new RecordSet();
        String requestid = requestInfo.getRequestid();
        String requestname = "";
        String workflowid = "";
        String formid = "";
        String creater = "";
        String createdate = "";
        String createtime = "";

        //获取流程基础信息
        String sqls = " select wr.requestname,wr.workflowid,wb.formid, wr.creater,wr.createdate,wr.createtime from WORKFLOW_REQUESTBASE  wr ,workflow_base wb " +
                " where  requestid='" + requestid + "' and wr.workflowid =wb.id ";
        //  Console.log(sqls);
        rst.execute(sqls);
        if (rst.next()) {
            requestname = rst.getString("requestname");
            workflowid = rst.getString("workflowid");
            formid = rst.getString("formid");
            creater = rst.getString("creater");
            createdate = rst.getString("createdate");
            createtime = rst.getString("createtime");
        }

        //获取流程主表表名
        sqls = "select tablename  from WORKFLOW_BILL where WORKFLOW_BILL.id='" + formid + "'";
        rst.execute(sqls);
        //Console.log(sqls);
        rst.first();
        String tablename = rst.getString("tablename");
        wsBaseInfo.setFormTablename(tablename);


        //获取流程主表数据
        sqls = "select  *  from " + tablename + " where requestid='" + requestid + "'";
        rst.execute(sqls);
        // Console.log(sqls);
        if (rst.next()) {
            String cloumn[] = rst.getColumnName();
            for (String c : cloumn) {
                String name = c.toLowerCase();
                String value = Util.null2String(rst.getString(c));
                mainMap.put(name, Util.null2String(value));
            }
        }


        sqls = "select detailtable from WORKFLOW_BILLFIELD where billid ='" + formid + "' and (detailtable is not null or detailtable <>''）  group by detailtable order by  detailtable";
        rst.execute(sqls);
        while (rst.next()) {
            String detailtablename = Util.null2String(rst.getString("detailtable"));
            //  Console.log("detailtablename："+detailtablename);
            if (!detailtablename.equals("")) {
                HashMap<String, HashMap<String, String>> rowList = new LinkedHashMap<String, HashMap<String, String>>();
                String sql = "select  dt.*  from " + detailtablename + " dt," + tablename + " t  where  t.id=dt.mainid and t.requestid='" + requestid + "'";
                rs.execute(sql);
                //  Console.log(sql);
                while (rs.next()) {
                    String cloumnArr[] = rs.getColumnName();
                    HashMap<String, String> rowMap = new LinkedHashMap<String, String>();
                    for (String c : cloumnArr) {
                        String name = c.toLowerCase();
                        String value = Util.null2String(rs.getString(c));
                        rowMap.put(name, Util.null2String(value));
                    }
                    rowList.put(rs.getString("id"), rowMap);
                }
                detailMap.put(detailtablename.substring(detailtablename.lastIndexOf("_") + 1), rowList);
            }
        }


        Console.log("jdbc 取值 mainMap:" + mainMap.toString());
        Console.log("jdbc 取值 detailMap:" + detailMap.toString());


    }


    /**
     * 获取选择框字段的文本
     *
     * @param fieldname   主表直接写字段数据库名称，明细表需要拼接明细表 例如  formtable_main_199_dt1.id  标识明细1的id
     * @param selectvalue
     * @param index
     * @return
     */
    private static String getSeletItemValue(String fieldname, String selectvalue, Integer index) {
        String name = "";

        try {
            RecordSet recordSet = new RecordSet();
            if (selectvalue.equals("null") || selectvalue == null) {
                selectvalue = "";
            }

            String detailtable = "";
            String fname = fieldname;
            String billid = "";
            if (fieldname.contains(".")) {
                detailtable = fieldname.split("\\.")[0];
                fname = fieldname.split("\\.")[1];
            }

            String sqls = "select * from workflow_billfield where billid= '" + wf_formid + "' and lower(FIELDNAME)='" + fname + "' ";
            if (detailtable.equals("")) {
                sqls = sqls + " and detailtable is null ";
            } else {
                sqls = sqls + " and detailtable like  '%" + detailtable + "'";
            }


            recordSet.execute(sqls);
            if (recordSet.first()) {
                billid = recordSet.getString("id");
            }

            sqls = "select * from WORKFLOW_SELECTITEM where selectvalue='" + selectvalue + "' and FIELDID='" + billid + "'";

            // Console.log(sqls);
            recordSet.execute(sqls);
            if (recordSet.first()) {
                name = recordSet.getString("selectName");
            }

            if (index != null && !name.isEmpty() && name.contains("|")) {
                name = name.split("\\|")[index];
            }
        } catch (Exception var11) {
        }

        return name.trim();
    }

    protected static String getSeletItemValue(String fieldname, String selectvalue) {
        return getSeletItemValue(fieldname, selectvalue, (Integer) null);
    }

    protected static String getSeletItemValueBefore(String fieldname, String selectvalue) {
        return getSeletItemValue(fieldname, selectvalue, 0);
    }

    protected static String getSeletItemValueAfter(String fieldname, String selectvalue) {
        return getSeletItemValue(fieldname, selectvalue, 1);
    }


    /**
     * 触发一个集成流程报错的提醒
     *
     * @param requestid
     */
    public static void sendActionErrorInfo(final int requestid) {

        Boolean istrue = true;
        String sendErrorWfCode = "," + Util.null2String(new BaseBean().getPropValue("customPropSet", "sendErrorWf"), "0") + ",";
        String sqlstr = "select WORKFLOWID from  workflow_requestbase where requestid='" + requestid + "'";
        RecordSet recordSet = new RecordSet();
        recordSet.execute(sqlstr);
        if (recordSet.next()) {
            if (sendErrorWfCode.contains("," + recordSet.getString("WORKFLOWID") + ",")) {
                //当为设置的流程wrokflow时
                istrue = false;
            }
        }
        if (sendErrorWfCode.equals(",0,")) {
            istrue = true;
        }
        if (istrue) {
            new Thread((new Runnable() {
                @Override
                public void run() {
                    String remarkfs = ""; //发送报文内容
                    try {

                        WorkflowRequestComInfo requestComInfo = new WorkflowRequestComInfo();
                        String requestname = "【流程Action集成报错】：相关请求\"" + requestComInfo.getRequestName("" + requestid) + "(" + requestid + ")\"";
                        String remark = requestname + "</br>操作时间:" + CustomUtil.getStringDate("yyyy-MM-dd HH:mm:ss") + "";
                        remark += "</br>相关请求:<a target=\"_blank\" href=\"/spa/workflow/static4form/index.html?#/main/workflow/req?requestid=" + requestid + "&ismonitor=1\">" + requestid + "</a>";

                        InetAddress addr = InetAddress.getLocalHost();
                        String ip = addr.getHostAddress().toString(); //获取本机ip
                        String hostName = addr.getHostName().toString(); //获取本机计算机名称
                        remark += "</br>执行服务器IP:" + ip;
                        remark += "</br>服务主机名:" + hostName;


                        int resourceid = Util.getIntValue(Util.null2String(new BaseBean().getPropValue("customPropSet", "actionResourceid")), 1);
                        setSysRemindInfo(requestname, resourceid, remark);
                        // 设置主表信息


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            })).start();
        }

    }

    /**
     * 项目提醒工作流
     *
     * @param requestname 工作流标题
     * @param resource    提醒人
     * @param remark      备注
     * @throws Exception
     */
    public static void setSysRemindInfo(String requestname, int resource, String remark) throws Exception {
        new weaver.system.SysRemindWorkflow().setSysRemindInfo(requestname, 0, 0, 0, 0, resource, "" + resource, remark);
    }

    /**
     * 更新主表流程字段的值
     *
     * @param params
     */
    protected void updateMainTableData(HashMap<String, String> params) {

        String fromtable = wsBaseInfo.getFormTablename();//表单
        String requestid = Util.null2String(mainMap.get("requestid"));
        String updatefields = "";
        String seclectFields = "";
        for (Map.Entry<String, String> e : params.entrySet()) {
            updatefields += "," + e.getKey() + "='" + e.getValue() + "'";
            seclectFields = "," + e.getKey();
        }

        if (updatefields.startsWith(",")) {
            updatefields = updatefields.substring(1);
            seclectFields = seclectFields.substring(1);
        }
        if (requestid != "" && fromtable != "" && updatefields != "") {
            RecordSet rs = new RecordSet();
            String secSQL = "select " + seclectFields + " from " + fromtable + " where   requestid='" + requestid + "'";
            rs.execute(secSQL);
            rs.first();
            String[] sf = seclectFields.split(",");
            writeLog("(" + requestid + ")更新前的值:");
            for (String s : sf) {
                writeLog(s + ":" + rs.getString("s"));
            }
            String updSQL = "update " + fromtable + " set " + updatefields + " where   requestid='" + requestid + "'";
            writeLog("(" + requestid + ")本次更新的SQL语句:" + updSQL);
            rs.execute(updSQL);

        } else {
            Console.log("参数不完整，不更新数据");

        }

    }


    /**
     * 更新主表流程字段的值
     *
     * @param arrayList
     */
    protected JSONObject getMainTableData(ArrayList<String> arrayList) {
        JSONObject result = new JSONObject();
        result.put("stauts", 0);
        String fromtable = wsBaseInfo.getFormTablename();//表单
        String requestid = Util.null2String(mainMap.get("requestid"));
        if (requestid != "" && fromtable != "") {
            RecordSet rs = new RecordSet();
            String secSQL = "select * from " + fromtable + " where   requestid='" + requestid + "'";
            rs.execute(secSQL);
            if (rs.next()) {
                for (String field : arrayList) {
                    String v = rs.getString(field);
                    result.put(field, v);
                }
            } else {
                result.put("stauts", 1);
            }
        } else {
            Console.log("参数不完整，不更新数据");

        }
        return result;
    }


    ///-----------

    public static JSONObject getMainTableData(String fromtable, String requestid, ArrayList<String> arrayList) {
        JSONObject result = new JSONObject();
        result.put("stauts", 0);


        if (requestid != "" && fromtable != "") {
            RecordSet rs = new RecordSet();
            String secSQL = "select * from " + fromtable + " where   requestid='" + requestid + "'";
            rs.execute(secSQL);
            if (rs.next()) {
                for (String field : arrayList) {
                    String v = rs.getString(field);
                    result.put(field, v);
                }
            } else {
                result.put("stauts", 1);
            }
        } else {
            Console.log("参数不完整，不更新数据");

        }
        return result;
    }


    public static void updateMainTableData(String fromtable, String requestid, HashMap<String, String> params) {
        String updatefields = "";
        String seclectFields = "";
        for (Map.Entry<String, String> e : params.entrySet()) {
            updatefields += "," + e.getKey() + "='" + e.getValue() + "'";
            seclectFields = "," + e.getKey();
        }

        if (updatefields.startsWith(",")) {
            updatefields = updatefields.substring(1);
            seclectFields = seclectFields.substring(1);
        }
        if (requestid != "" && fromtable != "" && updatefields != "") {
            RecordSet rs = new RecordSet();
            String secSQL = "select " + seclectFields + " from " + fromtable + " where   requestid='" + requestid + "'";
            rs.execute(secSQL);
            rs.first();
            String[] sf = seclectFields.split(",");
            Console.log("(" + requestid + ")更新前的值:");
            for (String s : sf) {
                Console.log(s + ":" + rs.getString("s"));
            }
            String updSQL = "update " + fromtable + " set " + updatefields + " where   requestid='" + requestid + "'";
            Console.log("(" + requestid + ")本次更新的SQL语句:" + updSQL);
            rs.execute(updSQL);

        } else {
            Console.log("参数不完整，不更新数据");

        }

    }


    public static void insertFnaVoucher_Del(String pzh, String nf, String gsdm,String requestid) {
        try{
          RecordSet rs=new RecordSet();
          String  usql="select qzlc,mxid  from uf_fnaVoucher where pzh='"+pzh+"'  and nf='"+nf+"'  and gsdm='"+gsdm+"'";
          rs.execute(usql);
          boolean b=false;
          if(rs.next()){
              b=true;
          }
          if(!b){
              String ins = "insert INTO  uf_fnaVoucher(pzh,nf,gsdm,qzlc)values('" + pzh + "','" + nf + "','" + gsdm + "','" + requestid + "')";
              Console.log(ins);
              rs.execute(ins);
          }
          rs.execute("update uf_fp  set pzhm='"+pzh+"',kjnd='"+nf+"',gsdm='"+gsdm+"' where zylc='"+requestid+"'");
        }catch (Exception e){

        }
    }


    /**
     * 获取选择框字段的文本
     *
     * @param fieldname   主表直接写字段数据库名称，明细表需要拼接明细表 例如  formtable_main_199_dt1.id  标识明细1的id
     * @param selectvalue
     * @param index
     * @return
     */
    public static String getSeletItemValue(String formid, String fieldname, String selectvalue, Integer index) {
        String name = "";

        try {
            RecordSet recordSet = new RecordSet();
            if (selectvalue.equals("null") || selectvalue == null) {
                selectvalue = "";
            }

            String detailtable = "";
            String fname = fieldname;
            String billid = "";
            if (fieldname.contains(".")) {
                detailtable = fieldname.split("\\.")[0];
                fname = fieldname.split("\\.")[1];
            }

            String sqls = "select * from workflow_billfield where billid= '" + formid + "' and lower(FIELDNAME)='" + fname + "' ";
            if (detailtable.equals("")) {
                sqls = sqls + " and detailtable is null ";
            } else {
                sqls = sqls + " and detailtable like  '%" + detailtable + "'";
            }


            recordSet.execute(sqls);
            if (recordSet.first()) {
                billid = recordSet.getString("id");
            }

            sqls = "select * from WORKFLOW_SELECTITEM where selectvalue='" + selectvalue + "' and FIELDID='" + billid + "'";

            // Console.log(sqls);
            recordSet.execute(sqls);
            if (recordSet.first()) {
                name = recordSet.getString("selectName");
            }

            if (index != null && !name.isEmpty() && name.contains("|")) {
                name = name.split("\\|")[index];
            }
        } catch (Exception var11) {
        }

        return name.trim();
    }

    public static String getSeletItemValue(String formid, String fieldname, String selectvalue) {
        return getSeletItemValue(formid, fieldname, selectvalue, (Integer) null);
    }

    public static String getSeletItemValueBefore(String formid, String fieldname, String selectvalue) {
        return getSeletItemValue(formid, fieldname, selectvalue, 0);
    }

    public static String getSeletItemValueAfter(String formid, String fieldname, String selectvalue) {
        return getSeletItemValue(formid, fieldname, selectvalue, 1);
    }


    public static void saveActionLog(RequestInfo request) {

        int MODEDATACREATER = request.getRequestManager().getUser().getUID();
        String MODEDATACREATEDATE = request.getRequestManager().getCurrentDate();
        String MODEDATACREATETIME = request.getRequestManager().getCurrentTime();
        String messageContent = request.getRequestManager().getMessagecontent();
        String requestid = request.getRequestid();
        int nodeid = request.getRequestManager().getNodeid();
        RecordSet rs = new RecordSet();
        String FORMMODEID = "";
        rs.execute(" update uf_actionerrorlog  set status=0 where nodeid='" + nodeid + "' and wfid='" + requestid + "' ");
        Console.log("MODEDATACREATER:" + MODEDATACREATER);
        Console.log("MODEDATACREATEDATE:" + MODEDATACREATEDATE);
        Console.log("MODEDATACREATETIME:" + MODEDATACREATETIME);
        Console.log("messageContent:" + messageContent);
        Console.log("requestid:" + requestid);
        Console.log("nodeid:" + nodeid);

        try {
            boolean ok = rs.executeQuery(" insert  into uf_actionerrorlog ( " +
                            " FORMMODEID,MODEDATACREATER, MODEDATACREATEDATE," +
                            " MODEDATACREATETIME,wfid,BCXX,nodeid ) values (?,?,?,?,?,?,?) ",
                    FORMMODEID, MODEDATACREATER, MODEDATACREATEDATE,
                    MODEDATACREATETIME, requestid, messageContent,
                    nodeid);
            Console.log("insert error log:" + ok);
        } catch (Exception e) {


        }

    }

    public synchronized int getRequestid(int reqeustid) {
        RecordSet rst = new RecordSet();
        rst.execute("select requestmark from workflow_requestbase  where requestid='" + reqeustid + "' ");
        rst.first();
        String requestmark = rst.getString("requestmark");
        requestmark = "FI00";
        String sql = "select max(wfid) as wfid from uf_cbs_pay where wfid like '%" + reqeustid + "'  and workflowNumber='" + requestmark + "'";
        rst.execute(sql);
        rst.first();
        int reqId = rst.getInt("wfid");

        if (reqId == -1) {//如果没有查到值 返回requestid
            reqId = reqeustid;
        } else if (reqId < 1000000000) {
            reqId = 1000000000 + reqId;
        } else if (reqId > 1000000000 && reqId < 2100000000) {
            reqId = reqId + 100000000;
        } else if (reqId > 2100000000 && reqId < 2120000000) {
            reqId = reqId + 10000000;
        } else if (reqId > 2120000000) {
            reqId = reqId + 1000000;
        }

        sql = "insert into uf_cbs_pay (wfid,workflowNumber) values('" + reqId + "','" + requestmark + "') ";
        rst.execute(sql);
        return reqId;
    }

    public String getWorkcode(int userid) {

        RecordSet rst = new RecordSet();
        String workcode = "";
        String accounttype = "";
        String belongto = "";
        rst.execute("select accounttype,workcode,belongto from  hrmresource  where id='" + userid + "' ");

        if (rst.next()) {
            accounttype = rst.getString("accounttype");
            workcode = rst.getString("workcode");
            belongto = rst.getString("belongto");
        }
        if (accounttype.equals("1")) {
            rst.execute("select  workcode  from  hrmresource   where  id='"+belongto+"' ");

            if (rst.next()) {
                workcode = rst.getString("workcode");
            }
        }

        return workcode;
    }

    public String getErrorInfo() {
        SimpleDateFormat CurrentDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String datetime = CurrentDate.format(date);
        String info = "提交时间:" + datetime + ";";

        try {
            InetAddress      addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress().toString(); //获取本机ip
            ip = ip.substring(ip.lastIndexOf(".") + 1);
            info += "执行服务器:" + ip + "</br>";
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return info;
    }


}

